#import "SEGWinningPublicDetailView.h"

@implementation SEGWinningPublicDetailViewModel
-(instancetype)init{
    if (self == [super init]) {
        _detailsText = @"";
        _picUrlString = @"";
    }
    return self;
}
@end

@implementation SEGWinningPublicDetailViewLayout
- (instancetype)initWithData:(SEGWinningPublicDetailViewModel *)data type:(SEGEnumWinningPublicDetailViewType)type{
    if (self == [super init]) {
        _data = data;
        _type = type;
    }
    [self segWinningPublicDetailViewLayout];
    return self;
}

-(void)segWinningPublicDetailViewLayout{
    //高度固定
    _totalHeight = kWinningPublicDetailViewHeight;
    
    //高度不固定
    //_totalHeight = 0;
    _detailsLabelHeight = 0;
    _detailsLabelTextLayout = nil;
    _webViewHeight = 10;
    
    if (!_data) return;
    
    [self layout];
}
//数据处理
-(void)layout
{
//    [self segDetailsLabelWithContent:_data.detailsText fontSize:13 textColor:kColor_1];
    _totalHeight = _webViewHeight + 30;
}

//控件detailsLabel文本布局计算
-(void)segDetailsLabelWithContent:(NSString*)content fontSize:(CGFloat)fontSize textColor:(UIColor*)color{
    if(!content)return;
    UIFont *font = [UIFont fontWithName:@"Heiti SC" size:fontSize];
    //过滤的特殊格式
    NSMutableAttributedString* text = [[NSMutableAttributedString alloc] initWithData:[content dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType } documentAttributes:nil error:nil];
//    self.describleLabel.attributedText = attributedString;
    
//    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:content];
    text.yy_font = font;
    text.yy_color = color;
    
    SEGContentTextLinePositionModifier *modifier = [SEGContentTextLinePositionModifier new];
    modifier.font = font;
    modifier.paddingTop = 1;
    
    SEGTextContainer *container = [SEGTextContainer new];
    container.size = CGSizeMake(LYScreenWidth()-30, HUGE);
    container.linePositionModifier = modifier;
    
    _detailsLabelTextLayout = [SEGTextLayout layoutWithContainer:container text:text];
    if (!_detailsLabelTextLayout)return;
    _detailsLabelHeight = [modifier heightForLineCount:_detailsLabelTextLayout.rowCount];
}
@end


@implementation SEGWinningPublicDetailView
- (instancetype)initWithFrame:(CGRect)frame {
    if (frame.size.width == 0 && frame.size.height == 0) {
        frame.size.width = [UIScreen mainScreen].bounds.size.width;
        frame.size.height = kWinningPublicDetailViewHeight;
    }
    self = [super initWithFrame:frame];
    
    [self addSubview:self.detailsLabel];
    [self addSubview:self.webView];
    
//    [self addSubview:self.picView];
    
    /*
     self.userInteractionEnabled = YES;
     __weak typeof(self) _self = self;
     UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithActionBlock:^(UITapGestureRecognizer*  _Nonnull sender) {
     [SEGAlertView showTmepMessageWithMessage:@"SEGWinningPublicDetailViewClick"];
     }];
     [self addGestureRecognizer:tap];
     */
    self.backgroundColor = kColor_W;
    return self;
}

-(void)setWithLayout:(SEGWinningPublicDetailViewLayout *)layout{
    self.height = layout.totalHeight;
    _layout = layout;
    
    if (self.height <= 0) return;
    
    self.detailsLabel.textLayout = layout.detailsLabelTextLayout;
//    [self.picView setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"-@-@",kClientImageRootURL,@""]] placeholderImage:[UIImage imageWithContentsOfFile:SEGPicName(@"")]];
    NSString *url = [NSString stringWithFormat:@"<body style='margin:0;padding:0'>%@</body>",layout.data.detailsText];//去除左右默认间距
    [self.webView loadHTMLString:url baseURL:nil];
    
    [self setupUI];
}

//界面布局
-(void)setupUI{

//    [self.webView mas_remakeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self).mas_offset(15);
//        make.bottom.equalTo(self).mas_offset(-15);
//        make.left.equalTo(self).mas_offset(15);
//        make.right.equalTo(self).mas_offset(-15);
//    }];

//    [self.picView mas_remakeConstraints:^(MASConstraintMaker *make) {
//        make.top.left.right.equalTo(self.bannerImageView.superview);
//        make.height.mas_equalTo(0);
//    }];
    
//    [self.detailsLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self).mas_offset(15);
//        make.bottom.equalTo(self).mas_offset(-15);
//        make.left.equalTo(self).mas_offset(15);
//        make.right.equalTo(self).mas_offset(-15);
//    }];
//
//    self.detailsLabel.textAlignment = NSTextAlignmentCenter;
//    self.detailsLabel.textVerticalAlignment = SEGTextVerticalAlignmentCenter;

}

-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    NSString *injectionJSString = @"var script = document.createElement('meta');"
    "script.name = 'viewport';"
    "script.content=\"width=device-width, user-scalable=no\";"
    "document.getElementsByTagName('head')[0].appendChild(script);";
    [webView evaluateJavaScript:injectionJSString completionHandler:nil];
}

//图片适配
- (void)setWebViewHtmlImageFitPhone
{
    NSString *jsStr = [NSString stringWithFormat:@"var script = document.createElement('script');"
                       "script.type = 'text/javascript';"
                       "script.text = \"function ResizeImages() { "
                       "var myimg,oldwidth;"
                       "var maxwidth = '%f';" //自定义宽度
                       "for(i=0;i <document.images.length;i++){"
                       "myimg = document.images[i];"
                       "if(myimg.width > maxwidth){"
                       "oldwidth = myimg.width;"
                       "myimg.width = maxwidth;"
                       "}"
                       "}"
                       "}\";"
                       "document.getElementsByTagName('head')[0].appendChild(script);",LYScreenWidth()-30];
    
//    [self.webView stringByEvaluatingJavaScriptFromString:jsStr];
//    [self.webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];
    
    [self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable req, NSError * _Nullable error) {
    }];
    [self.webView evaluateJavaScript:@"ResizeImages();" completionHandler:^(id _Nullable req, NSError * _Nullable error) {
    }];
}

#pragma mark - KVO动态监听网页的高度
- (void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context{
    if ([keyPath isEqualToString:@"contentSize"]) {
        [self.webView setFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, self.webView.scrollView.contentSize.height)];
        [self setWebViewHtmlImageFitPhone];
        CGFloat totalHeight = self.webView.scrollView.contentSize.height + 30;
        if (self.delegate && [self.delegate respondsToSelector:@selector(changeHeightTo:)]) {
            [self.delegate changeHeightTo:totalHeight];
        }
    }
}


#pragma mark - getter
-(SEGLabel *)detailsLabel{
    if (!_detailsLabel) {
        _detailsLabel = [[SEGLabel alloc]init];
        _detailsLabel.userInteractionEnabled = NO;
        _detailsLabel.textAlignment = NSTextAlignmentCenter;
        _detailsLabel.textVerticalAlignment = SEGTextVerticalAlignmentCenter;
        _detailsLabel.displaysAsynchronously = YES;
        _detailsLabel.ignoreCommonProperties = YES;//YES会影响系统属性
        _detailsLabel.fadeOnHighlight = NO;
        _detailsLabel.numberOfLines = 0;
        _detailsLabel.fadeOnAsynchronouslyDisplay = NO;
        _detailsLabel.fadeOnAsynchronouslyDisplay = NO;
        //if (kDebug)_detailsLabel.backgroundColor = kSegRandomColor;
        //__weak typeof(self) _self = self;
        //_detailsLabel.textTapAction = ^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        //[SEGAlertView showTmepMessageWithMessage:@"_detailsLabelClick"];
        //if (_self.delegate && [_self.delegate respondsToSelector:@selector(SEGprotocoldetailsLabel:)]) {
        //[_self.delegate SEGprotocoldetailsLabel:_self.detailsLabel];
        //}
        //};
    }
    return _detailsLabel;
}

- (WKWebView *)webView
{
    if (!_webView) {
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        NSString *jSString = [NSString stringWithFormat:@"var script = document.createElement('script');"
                              "script.type = 'text/javascript';"
                              "script.text = \"function ResizeImages() { "
                              "var myimg,oldwidth;"
                              "var maxwidth = '%f';" //自定义宽度
                              "for(i=0;i <document.images.length;i++){"
                              "myimg = document.images[i];"
                              "if(myimg.width > maxwidth){"
                              "oldwidth = myimg.width;"
                              "myimg.width = maxwidth;"
                              "}"
                              "}"
                              "}\";"
                              "document.getElementsByTagName('head')[0].appendChild(script);",LYScreenWidth()-30];
        NSString *jSString1 = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
        //用于进行JavaScript注入
        WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:[NSString stringWithFormat:@"%@",jSString] injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        [config.userContentController addUserScript:wkUScript];
        
        _webView = [[WKWebView alloc] initWithFrame:CGRectMake(15, 15, CGRectGetWidth(self.frame) - 30, 100) configuration:config];
        _webView.backgroundColor = [UIColor redColor];
        _webView.navigationDelegate = self;
        _webView.scrollView.showsHorizontalScrollIndicator = NO;
        _webView.scrollView.showsVerticalScrollIndicator = NO;
        _webView.scrollView.scrollEnabled = NO;
        _webView.scrollView.bounces = NO;
        [_webView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
    }
    return _webView;
}


//-(UIImageView *)picView{
//    if (!_picView) {
//        _picView = [[UIImageView alloc]init];
//        _picView.image = [UIImage imageWithContentsOfFile:SEGPicName(@"")];
//        _picView.contentMode = UIViewContentModeScaleAspectFill;
//        //_picView.layer.masksToBounds = YES;
//        //_picView.layer.cornerRadius = 0.5;
//        //if (kDebug)_picView.backgroundColor = kSegRandomColor;
//    }
//    return _picView;
//}

-(void)dealloc{
    [self.webView.scrollView removeObserver:self forKeyPath:@"contentSize"];
}
@end
